package com.yk.spark.util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Limit on 2017/9/8.
 */
public class HdfsUtil {
    private String HADOOP_MASTER_ADDRESS="hdfs://master.hadoop:9000";
    private FileSystem fileSystem;

    public HdfsUtil(String master) {
        this.HADOOP_MASTER_ADDRESS=master;
        try {
            this.fileSystem=FileSystem.get(URI.create(HADOOP_MASTER_ADDRESS),new Configuration());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public HdfsUtil() {
        try {
            this.fileSystem=FileSystem.get(URI.create(HADOOP_MASTER_ADDRESS),new Configuration());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean createDir(String current){

        boolean result=false;
        Path path = new Path(HADOOP_MASTER_ADDRESS+current);
        try {
            if(!this.fileSystem.exists(path)){
                result= this.fileSystem.mkdirs(path);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean deleteDir(String current){
        boolean result=false;

        Path path = new Path(HADOOP_MASTER_ADDRESS+current);
        try {
            if(this.fileSystem.exists(path)){
                result=this.fileSystem.delete(path,true);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public FileStatus queryCurrentFileStatus(String path){
        try {
            return this.fileSystem.getFileStatus(new Path(HADOOP_MASTER_ADDRESS+path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new FileStatus();
    }

    public List<FileStatus> queryChildrenFileStatus(String path){
        try {
            return Arrays.asList(this.fileSystem.listStatus(new Path(HADOOP_MASTER_ADDRESS+path)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    public void close(){
        try {
            this.fileSystem.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
